package com.zj.joke.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipInputStream;

import android.R.integer;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteException;
import android.widget.Toast;

import com.activeandroid.ActiveAndroid;
import com.zj.joke.Consts;
import com.zj.joke.R;

public class DBUtils {
	private static final String dbName = "jsoupdemo.db";

	public static boolean copyDB(Context context) {
		boolean result = false;
		try {
			SharedPreferences preferences = context.getSharedPreferences(
					Consts.SP_NAME, Context.MODE_PRIVATE);
			int localDBVersion = preferences.getInt(
					Consts.SP_KEY_LAST_DB_VERSION, -1);
			int lastDBVersion = ActiveAndroid.getDatabase().getVersion();
			{
				Editor editor = preferences.edit();
				editor.putInt(Consts.SP_KEY_LAST_DB_VERSION, ActiveAndroid
						.getDatabase().getVersion());
				editor.commit();
			}
			if (localDBVersion < lastDBVersion) {
				ActiveAndroid.dispose();
				String dbParentPath = context.getDatabasePath(dbName)
						.getParent();
				File dir = new File(dbParentPath);
				if (!dir.exists()) {
					dir.mkdir(); // create directory
				}
				String databaseFilename = context.getDatabasePath(dbName)
						.getPath();// 数据库文件路径
				// if (!(new File(databaseFilename).exists())) {
				System.out.println("begin to write db ..");

				FileOutputStream fos = null;
				fos = new FileOutputStream(databaseFilename); // 写入流
				InputStream is = context.getResources().openRawResource(
						R.raw.jsoupdemo);
				// sqlite 数据库文件大小不可超过 1mb. 这里采用先压缩成zip,再解压数据库
				ZipInputStream zipInputStream = new ZipInputStream(is);
				BufferedInputStream b = new BufferedInputStream(zipInputStream);
				int sourceLen = (int) zipInputStream.getNextEntry().getSize(); // 必须项
				byte[] buffer = new byte[1024 * 8];
				int count = 0, total = 0;
				try {
					while ((count = b.read(buffer)) > 0) {
						total += count;
						fos.write(buffer, 0, count);
						fos.flush();
					}
				} catch (Exception e) {
					System.out.println("read db failure." + e.getMessage());
				}
				System.out.println("writed db: " + total + "nsource len:"
						+ sourceLen);
				if (total == sourceLen) {
					System.out.println("read db successed.");
				}
				is.close();
				fos.close();
				result = true;
			}
		} catch (SQLiteException e) {
			System.out.println("SQLiteException:n" + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ActiveAndroid.initialize(context);
		}
		return result;
	}
}
